const withPlugins = require("next-compose-plugins");
const withSass = require('@zeit/next-sass')
const withCss = require("@zeit/next-css");
const withTM = require('next-transpile-modules');
const withTypescript = require('@zeit/next-typescript')
const path = require('path');
const cssLoaderGetLocalIdent = require("css-loader/lib/getLocalIdent.js");
const withBundleAnalyzer = require("@zeit/next-bundle-analyzer");

// 服务端、web端共同使用的配环境变量
// const publicConfig = require('./config/env/public/index')
// 服务端配置的环境变量
// const serverConfig = require('./config/env/server/index')

// 是否是生产环境
const isProd = process.env.NODE_ENV === 'production'


module.exports = withPlugins([withBundleAnalyzer, withTypescript, withCss, withSass, withTM], {
  cssModules: true,
  // 那些文件件可以当做页面
  pageExtensions: ['tsx'],
  // 将静态部分放到CDN
  assetPrefix: isProd ? 'https://cdn.wangyabin.top/YBWeb/view/web_next_app/' : '/',
  // 该配置只能在服务端使用
  // serverRuntimeConfig: serverConfig,
  // 该配置在服务端跟客户端都能使用
  // publicRuntimeConfig: publicConfig,
  cssLoaderOptions: {
    camelCase: true,
    localIdentName: "[local]___[hash:base64:5]",
    getLocalIdent: (context, localIdentName, localName, options) => {
      let hz = context.resourcePath.replace(context.rootContext, "");
      if (/node_modules/.test(hz)) {
        return localName;
      } else {
        return cssLoaderGetLocalIdent(
          context,
          localIdentName,
          localName,
          options
        );
      }
    }
  },
  webpack(config, options){
    if(config.externals){
      const includes = [/antd-mobile/];
      config.externals = config.externals.map(external => {
        if (typeof external !== 'function') return external;
        return (ctx, req, cb) => {
          return includes.find(include =>
            req.startsWith('.')
              ? include.test(path.resolve(ctx, req))
              : include.test(req)
          )
            ? cb()
            : external(ctx, req, cb);
        };
      });
    }
    // 别名
    config.resolve.alias['@components'] = path.resolve(__dirname, 'components')
    config.resolve.alias['@icons'] = path.resolve(__dirname, 'icons')
    config.resolve.alias['@ajax'] = path.resolve(__dirname, 'ajax')
    config.resolve.alias['@config'] = path.resolve(__dirname, 'config')
    config.resolve.alias['@utils'] = path.resolve(__dirname, 'utils')
    config.resolve.alias['@store'] = path.resolve(__dirname, 'store')
    config.resolve.alias['@styles'] = path.resolve(__dirname, 'styles')
    config.resolve.alias['@models'] = path.resolve(__dirname, 'models')

    return config;
  },
  // 查看打包的东西
  analyzeServer: ["server", "both"].includes(process.env.BUNDLE_ANALYZE),
  analyzeBrowser: ["browser", "both"].includes(process.env.BUNDLE_ANALYZE),
  bundleAnalyzerConfig: {
    server: {
      analyzerMode: "static",
      reportFilename: "../bundles/server.html"
    },
    browser: {
      analyzerMode: "static",
      reportFilename: "../bundles/client.html"
    }
  },
})

